package thoven.achievement.net.jsonutil.action

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.ui.Messages
import thoven.achievement.net.jsonutil.service.FormatConverter
import thoven.achievement.net.jsonutil.service.JsonCleaner

/**
 * JSON 转 YAML 的操作
 */
class JsonToYamlAction : AnAction() {
    
    override fun actionPerformed(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR) ?: return
        val project = e.project ?: return
        val document = editor.document
        
        val selectionModel = editor.selectionModel
        val selectedText = selectionModel.selectedText
        
        if (selectedText.isNullOrBlank()) {
            Messages.showWarningDialog(
                project,
                "请选择要转换的 JSON 文本",
                "JSON 转 YAML"
            )
            return
        }
        
        // 清理 JSON
        val cleanResult = JsonCleaner.clean(selectedText)
        if (cleanResult.isFailure) {
            Messages.showErrorDialog(
                project,
                "清理 JSON 失败: ${cleanResult.exceptionOrNull()?.message}",
                "转换错误"
            )
            return
        }
        
        val cleanedJson = cleanResult.getOrNull() ?: return
        val convertResult = FormatConverter.jsonToYaml(cleanedJson)
        
        if (convertResult.isSuccess) {
            val yaml = convertResult.getOrNull() ?: return
            
            WriteCommandAction.runWriteCommandAction(project) {
                document.replaceString(
                    selectionModel.selectionStart,
                    selectionModel.selectionEnd,
                    yaml
                )
            }
        } else {
            Messages.showErrorDialog(
                project,
                "转换失败: ${convertResult.exceptionOrNull()?.message}",
                "转换错误"
            )
        }
    }
    
    override fun update(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR)
        val hasSelection = editor?.selectionModel?.hasSelection() == true
        e.presentation.isEnabledAndVisible = hasSelection
    }
}

